<template>
  <section class="main">
    <input
      id="toggle-all"
      class="toggle-all"
      type="checkbox"
      v-model="isCheckAll"
    >
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <!-- 这些只是为了显示列表项的结构-->
      <!-- 列表项在编辑时应获得类“编辑”，在标记为完成时应获得“已完成”类 -->
      <li
       :class="{completed: item.isDone, editing: item.id === currentId}"
       v-for="item in showList"
       :key="item.id"
      >
        <div class="view">
          <input
           class="toggle"
           type="checkbox"
           :checked="item.isDone"
           @change="change(item.id)"
          >
          <label @dblclick="showEdit(item)">{{item.name}}</label>
          <button class="destroy" @click="del(item.id)"></button>
        </div>
        <input
          class="edit"
          v-model="currentName"
          @keyup.enter="edit"
          @keyup.esc="esc"
        >
      </li>
    </ul>
  </section>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      required: true,
    },
    type: {
      type: String,
      default: 'all'
    }
  },
  data() {
    return {
      currentId: '',
      currentName: ''
    }
  },
  methods: {
    del(id) {
      this.$emit('del', id)
    },
    change(id) {
      this.$emit('change', id)
    },
    showEdit(item) {
      this.currentId = item.id
      this.currentName = item.name
    },
    edit() {
      this.$emit('edit', this.currentId, this.currentName)
      this.currentId = ''
      this.currentName = ''
    },
    esc() {
      this.currentId = ''
    }
  },
  computed: {
    showList() {
      if(this.type === 'active') {
        return this.list.filter(item => !item.isDone)
      } else if(this.type === 'completed') {
        return this.list.filter(item => item.isDone)
      } else {
        return this.list
      }
    },
    isCheckAll: {
      get() {
        return this.list.every(item => item.isDone) 
      },
      set(value) {
        this.$emit('checkAll', value)
      }
    }
  }
}
</script>

<style>

</style>